/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.mapbox.ohos.gestures.testapp.slice;

import com.mapbox.ohos.gestures.testapp.ExclusiveSetSpinnerObject;

import ohos.agp.components.BaseItemProvider;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.LayoutScatter;
import ohos.agp.components.Text;
import ohos.app.Context;

import com.mapbox.ohos.gestures.testapp.ResourceTable;

import java.lang.ref.WeakReference;
import java.util.List;

/**
 * @since 2021-07-15
 */
public class MyProvider extends BaseItemProvider {

    private List<ExclusiveSetSpinnerObject> list;
    private WeakReference<Context> context;
    private ItemClick itemClick;

    public MyProvider(Context context, List<ExclusiveSetSpinnerObject> list) {
        this.context = new WeakReference(context);
        this.list = list;
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(int position) {
        return list.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public Component getComponent(int position, Component component, ComponentContainer componentContainer) {
        if (component == null) {
            component = LayoutScatter.getInstance(context.get()).parse(ResourceTable.Layout_layout_spinner_item,
                null, false);
        }

        Text mItemName = (Text) component.findComponentById(ResourceTable.Id_tv_item_name);
        mItemName.setText(list.get(position).toString());
        mItemName.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                itemClick.itemClick(component, position);
            }
        });
        return component;
    }

    public void setItemClick(ItemClick itemClick) {
        this.itemClick = itemClick;
    }

    public interface ItemClick {
        void itemClick(Component component, int position);
    }
}
